<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select v-model="roomQuery.building" placeholder="请选择区域" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter" @change="queryBuildingChange()">
        <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="roomQuery.floor" placeholder="请选择楼层" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="roomQuery.rno" placeholder="宿舍号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="区域" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.building }}
        </template>
      </el-table-column>
      <el-table-column label="楼层" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.floor }}
        </template>
      </el-table-column>
      <el-table-column label="宿舍号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.rno }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="当前人数" width="200">
        <template slot-scope="scope">
          {{ scope.row.current }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="容量" width="200">
        <template slot-scope="scope">
          {{ scope.row.capacity }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="openRoomImageDialog(row)">
            上传宿舍图片
          </el-button>
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="room" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="区域" prop="building">
          <el-select v-model="room.building" placeholder="请选择区域" clearable style="width: 300px;" @change="buildingChange()">
            <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-select v-model="room.floor" placeholder="请选择楼层" clearable style="width: 300px;">
            <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="rno">
          <el-input v-model="room.rno" />
        </el-form-item>
        <el-form-item label="当前人数" prop="current">
          <el-input-number v-model="room.current" controls-position="right" :max="8" :min="0" />
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="room.capacity" controls-position="right" :max="8" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="宿舍图片"
      :visible.sync="roomImageVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="closeRoomImageDialog"
      @close="closeRoomImageDialog"
    >
      <el-upload
        ref="upload"
        action="#"
        list-type="picture-card"
        :limit="4"
        :http-request="uploadFile"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        :on-exceed="onExceed"
        :file-list="fileList"
      >
        <i class="el-icon-plus" />
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getRoom, buildingList, floorListById, uploadRoomImage, removeRoomImage } from '@/api/room'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      roomQuery: {
        building: '',
        floor: '',
        rno: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      room: {
        id: '',
        building: '',
        floor: '',
        rno: '',
        current: '',
        capacity: ''
      },
      dialogFormVisible: false,
      rules: {
        building: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
        floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
        rno: [{ required: true, message: '宿舍号不能为空', trigger: 'blur' }],
        current: [{ required: true, message: '当前人数不能为空', trigger: 'blur' }],
        capacity: [{ required: true, message: '容量不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      buildingOptions: [],
      floorDisabled: true,
      floorOptions: [],
      roomImageVisible: false,
      fileList: [],
      roomId: ''
    }
  },
  created() {
    this.getList()
    buildingList().then((response) => {
      this.buildingOptions = response.data
    })
    // floorList().then((response) => {
    //   this.floorOptions = response.data
    // })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.roomQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    queryBuildingChange() {
      this.floorOptions = []
      this.roomQuery.floor = ''
      if (this.roomQuery.building !== '') {
        floorListById(this.roomQuery.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    buildingChange() {
      this.floorOptions = []
      this.room.floor = ''
      if (this.room.building !== '') {
        floorListById(this.room.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    handleCreate() {
      this.resetRoom()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetRoom() {
      this.room = {
        id: '',
        building: '',
        floor: '',
        rno: '',
        current: '',
        capacity: ''
      }
      this.floorDisabled = true
      this.floorOptions = []
    },
    // 添加或编辑后回显到表格的数据需要处理
    setBuilding(data) {
      this.buildingOptions.find((item) => {
        if (item.id === data.building) {
          data.building = item.name
          return
        }
      })
      this.floorOptions.find((item) => {
        if (item.id === data.floor) {
          data.floor = item.name
          return
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          save(this.room).then((response) => {
            this.setBuilding(response.data)
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      // 获取宿舍信息
      const res = await getRoom(row.id)
      this.room = res.data
      // 根据宿舍信息获取楼栋和楼层
      const floorList = await floorListById(this.room.building)
      this.floorDisabled = false
      this.floorOptions = floorList.data
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          update(this.room).then((response) => {
            this.setBuilding(response.data)
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['区域', '楼层', '宿舍号', '当前人数', '容量']
        const filterVal = ['building', 'floor', 'rno', 'current', 'capacity']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '宿舍信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    openRoomImageDialog(row) {
      this.roomId = row.id
      this.roomImageVisible = true
      this.getImgUrl(row.id)
    },
    getImgUrl(id) {
      getRoom(id).then((res) => {
        const urls = res.data.url
        if (urls !== '' || urls !== null) {
          urls.split(',').forEach((item) => {
            var obj = {}
            const index = item.lastIndexOf('/')
            const fileName = item.substring(index + 1, item.length) // 最后的文件名截取出来
            obj['name'] = fileName
            obj['url'] = item
            this.fileList.push(obj)
          })
        }
      })
    },
    closeRoomImageDialog() {
      this.roomImageVisible = false
      this.fileList = []
      this.roomId = ''
    },
    uploadFile(data) {
      const formdata = new FormData()
      formdata.append('file', data.file)
      formdata.append('id', this.roomId)
      uploadRoomImage(formdata).then((res) => {
        this.$notify({
          title: 'Success',
          message: '上传成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleRemove(file, fileList) {
      const formdata = new FormData()
      formdata.append('filename', file.name)
      formdata.append('id', this.roomId)
      removeRoomImage(formdata).then((res) => {
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    onExceed(files, fileList) {
      this.$message.error('图片最多上传4个!')
    },
    beforeUpload(file) {
      const isImg =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 4
      var reg = /^[0-9a-zA-Z.]+$/
      const filename = reg.test(file.name)
      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG/JPGE/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 4MB!')
      }
      if (!filename) {
        this.$message.error('文件名不能包含特殊字符!')
      }
      return isImg && isLt2M && filename
    }
  }
}
</script>
